//
//  SDEGORefreshTableHeaderView.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDEGORefreshTableHeaderView.h"

#import "SDDotAnimationView.h"

#define TEXT_COLOR [UIColor colorWithRed:142 / 255.0 green:142 / 255.0 blue:142 / 255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

#define EGORefreshTableHeaderViewStoreKey @"EGORefreshTableView_LastRefresh"

@interface SDEGORefreshTableHeaderView ()<SDDotAnimationViewDelegate> {
    UIImageView *_bgView;
    UIImageView *_topView;
    UIImageView *_loadingView;
}
@property(nonatomic, strong) SDDotAnimationView *dotView;
- (void)setState:(EGOPullRefreshState)aState;
@end

@implementation SDEGORefreshTableHeaderView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.backgroundColor = [UIColor clearColor];
        
        //        //helei begin
        //        UIImage *image1 =LOAD_IMAGE_USE_CACHE_INBUNDLE(TimelineBundle,@"loading_blue.png");
        //        UIImage *image2  = LOAD_IMAGE_USE_CACHE_INBUNDLE(TimelineBundle,@"loading_big_blue.png");
        //        NSArray *imageArray = [NSArray arrayWithObjects:image1,image2, nil];
        //        _loadingView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width-140)/2, 0,
        //        image2.size.width, image2.size.height)];
        //        self.backgroundColor = [UIColor clearColor];
        //        _loadingView.animationImages = imageArray;
        //        _loadingView.animationDuration = 0.3;
        //        _loadingView.animationRepeatCount = 0;
        //        _loadingView.center = self.center;
        //        [self addSubview:_loadingView];
        
        _dotView = [[SDDotAnimationView alloc] init];
        _dotView.delegate = self;
        _dotView.numberOfCircles = 3;
        //_dotView.radius = 6;
        //_dotView.internalSpacing = 10;
        [_dotView initViews];
        //[_dotView startAnimating];
        [_dotView sizeToFit];
        [self addSubview:_dotView];
        _dotView.centerX = self.width * 0.5;
        _dotView.centerY = self.height * 0.5;
        [self setState:EGOOPullRefreshNormal];
    }
    
    return self;
}

- (void)dealloc {
}

- (UIColor *)dotView:(SDDotAnimationView *)dotView circleBackgroundColorAtIndex:(NSUInteger)index {
    UIColor *color = nil;
    switch (index) {
        case 0: {
            color = [UIColor colorWithRed:254.0f / 255 green:203.0f / 255 blue:47.0f / 255 alpha:1];
            break;
        }
        case 1: {
            color = [UIColor colorWithRed:253.0f / 255 green:119.0f / 255 blue:136.0f / 255 alpha:1];
            break;
        }
        case 2: {
            color = [UIColor colorWithRed:108.0f / 255 green:149.0f / 255 blue:223.0f / 255 alpha:1];
            break;
        }
        default:
            break;
    }
    return color;
}

#pragma mark -
#pragma mark Setters

- (void)refreshLastUpdatedDate {
    
    if ([self.delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)]) {
        
        // if (self.lastUpdateDate == nil)
        { self.lastUpdateDate = [_delegate egoRefreshTableHeaderDataSourceLastUpdated:self]; }
        
        _lastUpdatedLabel.text = self.lastUpdateDate
        ? [NSString stringWithFormat:@"最近更新: %@",
           [SDNSString stringFromDate:self.lastUpdateDate]]
        : @"";
        
    } else {
        
        _lastUpdatedLabel.text = nil;
    }
}

- (void)refresh {
    // _statusLabel.text = [self.delegate egoRefreshTableHeaderTitle:self state:_state];
    switch (_state) {
            //		case EGOOPullRefreshPulling:
            //
            //
            //            //			[CATransaction begin];
            //            //			[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
            //            //			_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) *
            //            180.0f,
            //            0.0f,
            //            0.0f,
            //            1.0f);
            //            //			[CATransaction commit];
            //
            //			break;
        case EGOOPullRefreshNormal: {
            if (_state == EGOOPullRefreshPulling) {
            }
            [_dotView stopAnimating];
            
            //            UIImage *image1 =LOAD_IMAGE_USE_CACHE_INBUNDLE(TimelineBundle,@"loading_blue.png");
            //            _loadingView.image = image1;
            //            [_loadingView stopAnimating];
            //            _loadingView.animationImages = nil;
            //			self.lastUpdateDate = [NSDate date];
            //			if ([_delegate
            // respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)])
            //{
            //				self.lastUpdateDate = [_delegate
            // egoRefreshTableHeaderDataSourceLastUpdated:self];
            //			}
            //
            //			[self refreshLastUpdatedDate];
        } break;
        case EGOOPullRefreshLoading:
            [_dotView startAnimating];
            break;
        case EGOOPullRefreshPulling: {
            
            //            _loadingView.hidden = NO;
            //
            //            [_loadingView.layer removeAllAnimations];
            //            UIImage *image1 =LOAD_IMAGE_USE_CACHE_INBUNDLE(TimelineBundle,@"loading_blue.png");
            //            UIImage *image2  = LOAD_IMAGE_USE_CACHE_INBUNDLE(TimelineBundle,@"loading_big_blue.png");
            //            NSArray *imageArray = [NSArray arrayWithObjects:image1,image2, nil];
            //            _loadingView.animationImages = imageArray;
            //            _loadingView.image = nil;
            //            // _loadingView.hidden = YES;
            //            _loadingView.animationDuration = 0.3;
            //            _loadingView.animationRepeatCount = 0;
            //
            //            [_loadingView startAnimating];
            
            //            CABasicAnimation* rotationAnimation;
            //            rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            //            rotationAnimation.fromValue = [NSNumber numberWithFloat:0];
            //            rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
            //            rotationAnimation.duration = 1.0;
            //            rotationAnimation.cumulative = YES;
            //            rotationAnimation.repeatCount = HUGE_VALF;
            //
            //            [_loadingView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
            
        } break;
        default:
            
            break;
    }
}

- (void)setState:(EGOPullRefreshState)aState {
    
    _state = aState;
    [self refresh];
}

#pragma mark -
#pragma mark ScrollView Methods

- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {
    if (_state == EGOOPullRefreshForceLoading) {
        [self egoRefreshScrollViewDidEndDragging:scrollView];
    } else if (_state == EGOOPullRefreshLoading) {
        
        CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
        offset = MIN(offset, 60);
        UIEdgeInsets edgeInsets = scrollView.contentInset;
        edgeInsets.top = offset;
        scrollView.contentInset = edgeInsets;
        
    } else if (scrollView.isDragging) {
        //_loadingView.hidden = YES;
        if (scrollView.contentOffset.y > -65.0f && scrollView.contentOffset.y < 0.0f &&
            _state != EGOOPullRefreshLoading) {
            CGFloat percent = -(scrollView.contentOffset.y + 25.0) / 40.0;
            CGFloat height = floorf(21.5 * percent);
            _bgView.frame = CGRectMake(104.25, 19.25, 21.5, 21.5 - percent);
            _topView.frame = CGRectMake(104.25, 19.25 + 21.5 - height, 21.5, height);
        }
        
        if (scrollView.contentOffset.y < -65.0f) {
            _bgView.frame = CGRectMake(104.25, 19.25, 21.5, 0);
            _topView.frame = CGRectMake(104.25, 19.25, 21.5, 21.5);
        }
        
        BOOL _loading = NO;
        if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
            _loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
        }
        
        if (_state == EGOOPullRefreshPulling && scrollView.contentOffset.y > -65.0f &&
            scrollView.contentOffset.y < 0.0f && !_loading) {
            [self setState:EGOOPullRefreshNormal];
        } else if (_state == EGOOPullRefreshNormal && scrollView.contentOffset.y < -65.0f && !_loading) {
            [self setState:EGOOPullRefreshPulling];
        }
        
        if (scrollView.contentInset.top != 0) {
            UIEdgeInsets edgeInsets = scrollView.contentInset;
            edgeInsets.top = 0.0f;
            scrollView.contentInset = edgeInsets;
        }
        
        if (scrollView.contentOffset.y < 0) {
            [self refreshLastUpdatedDate];
        }
    }
}

- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
    BOOL _loading = NO;
    if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
        _loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
    }
    
    if (scrollView.contentOffset.y <= -65.0f && !_loading) {
        
        [self setState:EGOOPullRefreshLoading];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        UIEdgeInsets edgeInsets = scrollView.contentInset;
        edgeInsets.top = 60.0f;
        scrollView.contentInset = edgeInsets;
        [UIView commitAnimations];
        
        if (!_loading && [_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
            [_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
        }
    }
}

- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
    
    [UIView animateWithDuration:.5
                     animations:^{
                         UIEdgeInsets edgeInsets = scrollView.contentInset;
                         edgeInsets.top = 0.0f;
                         scrollView.contentInset = edgeInsets;
                     }
                     completion:^(BOOL finished) {
                         self.hidden = FALSE;
                         UIEdgeInsets edgeInsets = scrollView.contentInset;
                         edgeInsets.top = 0.0f;
                         scrollView.contentInset = edgeInsets;
                     }];
    [self setState:EGOOPullRefreshNormal];
}

- (void)forceLoading:(UIScrollView *)scrollView {
    self.isTriggerByDrag = NO;
    
    scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -65);
    [self egoRefreshScrollViewDidEndDragging:scrollView];
}

- (void)forceLoading:(UIScrollView *)scrollView animate:(BOOL)animate {
    self.isTriggerByDrag = NO;
    [self setState:EGOOPullRefreshForceLoading];
    
    [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, -65) animated:animate];
}

@end

